package org.autumn.review.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

public class AlternatePrint {
    static Thread t1;
    static Thread t2;
    static Thread t3;

    public static void main(String[] args) throws InterruptedException {
        Printer printer = new Printer(5);
        t1 = new Thread(() -> {
            printer.print("a", t2);
        }, "t1");


        t2 = new Thread(() -> {
            printer.print("b", t3);
        }, "t2");


        t3 = new Thread(() -> {
            printer.print("c", t1);
        }, "t3");

        t1.start();
        t2.start();
        t3.start();

        TimeUnit.SECONDS.sleep(2);
        LockSupport.unpark(t1);
    }
}

@Slf4j
class Printer {
    int loopNum;

    public Printer(int loopNum) {
        this.loopNum = loopNum;
    }

    public void print(String str, Thread next) {
        for (int i = 0; i < loopNum; i++) {
            LockSupport.park();
            log.info(str);
            LockSupport.unpark(next);
        }
    }
}
